import { app, shell, BrowserWindow, ipcMain, dialog, Menu } from "electron";
const path = require("path");
const fs = require("fs");
import COM from "../renderer/utils/com";
import { logs } from "../renderer/utils/logs";

process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

const com = new COM();
ipcMain.on("COM_CONNECT_ACTION", (e, paylod) => {
  console.log("COM_CONNECT_ACTION");
  com.COM_CONNECT_ACTION({ config: paylod, mainWindow: mainWindow });
});
ipcMain.on("COM_CLOSE_ACTION", (e) => {
  console.log("COM_CLOSE_ACTION");
  com.COM_CLOSE_ACTION();
});
async function handleFileOpen(config) {
  // const mothodMap = ['openFile', 'openDirectory', 'multiSelections']
  const method = config.mothod ? config.mothod : "openFile";
  const { canceled, filePaths } = await dialog.showOpenDialog({
    properties: [method],
  });
  if (canceled) {
    return;
  } else {
    if (config.type) {
      const files = await getFiles(filePaths, config.type, config.mothod);
      if (files.length > 200) {
        const choice = dialog.showMessageBoxSync(mainWindow, {
          type: "warning",
          buttons: ["确定"],
          title: "警告",
          message: "单次选的的图片超过上限!",
        });
        if (choice == 0) {
          return;
        }
      } else {
        return files; // 返回文件名给渲染进程
      }
    }
    return filePaths[0]; // 返回文件名给渲染进程
  }
}
async function getFiles(folderPath, type, mothod) {
  let files = [];
  if (mothod === "openFile") {
    files = [...folderPath];
  } else if (mothod === "multiSelections") {
    files = [...folderPath];
  } else if (mothod === "openDirectory") {
    const names = fs.readdirSync(folderPath[0]);

    files = names.map((file) => {
      const filePath = path.join(folderPath[0], file);

      return filePath;
    });
  }
  const imageFiles = files.filter((file) => {
    const fileExtension = path.extname(file).toLowerCase();

    if (type === "img") {
      return [".png", ".jpg", ".jpeg", ".bmp"].includes(fileExtension);
    }
  });

  const images = imageFiles.map((file) => {
    const name = file.split("\\").pop();
    return {
      name: name,
      path: file,
    };
  });
  return images;
}
ipcMain.handle("dialog:openFile", (e, type) => {
  return handleFileOpen(type);
});
ipcMain.handle("temp", (e, paylod) => {
  return app.getPath("temp");
});
ipcMain.handle("ai", (e, paylod) => {
  return process.env.NODE_AI;
});
ipcMain.handle("static", (e, paylod) => {
  const path = require("path");
  const basepath =
    process.env.NODE_ENV === "development"
      ? app.getAppPath()
      : path.join(app.getAppPath(), "/dist/electron");
  return path.join(basepath, "/static").replace(/\\/g, "\\\\");
});
ipcMain.handle("global", (e, paylod) => {
  return global[paylod];
});
ipcMain.handle("root", (e, paylod) => {
  // console.log(app.isPackaged, app.getAppPath());
  const rootPath = app.isPackaged
    ? app.getAppPath()
    : app.getAppPath().replace(/(.*)(?=\\resources)/, "");
  return rootPath;
});
ipcMain.handle("saveJson", (e, o) => {
  try {
    const data = fs.writeFileSync(o.filepath, o.data);
    return Promise.resolve();
  } catch (err) {
    return Promise.reject();
  }
});
ipcMain.handle("openDirectory", (e, path) => {
  return new Promise((resolve, reject) => {
    shell
      .openPath(path)
      .then(() => {
        console.log(`成功打开资源管理器并定位到路径: ${path}`);
        resolve(path);
      })
      .catch((err) => {
        console.error("无法打开资源管理器:", err);
        reject(err);
      });
  });
});

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== "development") {
  global.__static = require("path")
    .join(__dirname, "/static")
    .replace(/\\/g, "\\\\");
}
let title = "基因芯片数据分析软件"; // 默认标题
console.log(process.env.NODE_VERSION);
if (process.env.NODE_VERSION) {
  global.NODE_VERSION = process.env.NODE_VERSION;
  if (process.env.NODE_VERSION === "tester") {
    title = "基因芯片数据分析软件（研发专用）";
  } else if (process.env.NODE_VERSION === "gather") {
    title = "全自动核酸分子杂交仪采集软件V3.0.01.23.01.13";
  }
  console.log(title);
} else {
  global.NODE_VERSION = "";
}

let flag = true;

let mainWindow;
const winURL =
  process.env.NODE_ENV === "development"
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`;

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
} else {
  app.on("second-instance", (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
      mainWindow.show();
    }
  });
}
async function createWindow() {
  if (!gotTheLock) {
    return;
  }
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSercurity: false,
      devTools: true,
    },
  });

  mainWindow.setTitle(title);

  // 创建菜单模板
  const menuTemplate = [];

  // 根据菜单模板创建菜单
  const menu = Menu.buildFromTemplate(menuTemplate);

  // 设置应用程序的菜单
  Menu.setApplicationMenu(menu);

  mainWindow.loadURL(winURL);

  mainWindow.webContents.openDevTools()

  mainWindow.webContents.on("will-prevent-unload", (event) => {
    console.log("will-prevent-unload");
    com.COM_CLOSE_ACTION();
    flag = true;
    event.preventDefault();
    // const choice = dialog.showMessageBoxSync(mainWindow, {
    //   type: 'question',
    //   buttons: ['Leave', 'Stay'],
    //   title: 'Do you want to leave this site?',
    //   message: 'Changes you made may not be saved.',
    //   defaultId: 0,
    //   cancelId: 1
    // })
    // const leave = (choice === 0)
    // if (leave) {
    //   flag = true
    //   mainWindow.webContents.send('Com', 'COM_CLOSE_ACTION');
    //   event.preventDefault()
    // }
  });

  mainWindow.webContents.on("did-stop-loading", async () => {
    console.log("did-stop-loading");
    if (flag) {
      flag = false;
      await waitForBeforeUnload();
    }
  });

  mainWindow.on("close", (e) => {
    e.preventDefault();
    const choice = dialog.showMessageBoxSync(mainWindow, {
      type: "question",
      buttons: ["确定", "取消"],
      title: "提示",
      message: "确定要退出吗?",
    });
    if (choice == 0) {
      logs("关闭了软件");

      app.exit();
    }
  });

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}

// 等待 beforeunload 事件
function waitForBeforeUnload() {
  return new Promise((resolve, reject) => {
    mainWindow.webContents.executeJavaScript(
      `
      window.addEventListener('beforeunload', function (event) {
        console.log('页面要刷新了')
        event.returnValue = '您确定要离开此页面吗？';
      });
    `,
      true,
      () => {
        resolve();
      }
    );
  });
}

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  console.log("activate");
  if (mainWindow === null) {
    createWindow();
  }
});

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
